#encoding : utf-8

class BlogsController < ApplicationController

  # 显示blogs
  def list
    # 查数据，列表页
    @blogs = Blog.where(:status => '0').order('created_at desc').page(params[:page]).per(10)

    render 'blogs/index'
  end

  # 新增blog
  def new
    tags = Tags.all
    tag_h = Hash.new
    tags.each do |t|
      tag_h[t.name] = t.id
    end
    @tags = tag_h
  end

  # 创建blogs
  def create
    #a = Blogs::BlogInfo.create(blog_id: 2, blog_title: 'second blog', blog_content: 'the second blog ~~~~~~', user_id: 1, blog_created_at: Time.now )
    result = Blog.create(:title => params[:title], :content => params[:content], :uid => 1, :tags_id => params[:select_tags_id], :created_at => Time.now)
    unless result
      flash[:error] = '服务调用出错，请稍候再试'
      redirect_to new_blog_path
      return
    end
    redirect_to list_blogs_path
  end

  #显示blog
  def show
    #Blog(id: integer, user_base_info_id: integer, title: string, content: string, status: string, publish_status: string, uid: string, tags_id: string, created_at: datetime, updated_at: datetime)
    show_blog = Blog.find(params[:id])
    #获取评论数
    @comments = Comment.where(:blog_id => params[:id] ).order('ID ASC')

    #上一篇，下一篇
    # 添加 status = '0'
    up_blog = Blog.where('id < ? and status = ?', params[:id], '0').order('id DESC').first
    next_blog = Blog.where('id > ? and status = ?', params[:id], '0').order('id ASC').first

    #相关博文（相同tag的文章）
    tag_id = show_blog.tags_id
    @same_tag_blogs = Blog.where(:tags_id => tag_id, :status => '0').order('id ASC')

    @show_blog = show_blog
    @up_blog = up_blog
    @next_blog = next_blog
  end

  # 编辑blogs
  def edit
    #   在页面判断是否有登录，登录后才可修改（1. 博文是否对应uid， 2.或者提交后不能编辑）

    @edit_blog = Blog.find(params[:id])

    @tag = Tags.find(@edit_blog.tags_id)
    tags = Tags.all
    tag_h = Hash.new
    tags.each do |t|
      tag_h[t.name] = t.id
    end
    @tags = tag_h
  end


  # 更新blogs
  def update

  end

  # 删除blog
  def destroy

  end

  #保存草稿功能
  def save
    result = Blog.create(:title => params[:title], :content => params[:content], :uid => 1, :tags_id => params[:tags], :status => 2, :created_at => Time.now)
    unless result
      flash[:error] = '服务调用出错，请稍候再试'
      redirect_to new_blog_path
      return
    end
  end

  #草稿箱
  def drafts
    @show_drafts = Blog.where("status = '2'").order('created_at desc').page(params[:page]).per(5)
  end

  #评论
  def comment

  end
end